var $HyTools = (function () {
    var bootstrapTable_default = {
        method: 'GET',        //请求方式（*）
        ajaxOptions: {async: true},   //请求方法,默认异步
        toolbar: '#toolbar',  //工具按钮用哪个容器(默认toolbar)
        queryParamsType: 'limit',//限制queryParams的参数为： limit, offset, search, sort, order
        striped: true,        //是否显示行间隔色
        cache: false,         //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,     //是否显示分页（*）
        //search: true,         //搜索
        sortable: true,       //是否启用排序
        sortOrder: 'desc',            //排序方式
        sidePagination: 'server',    //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,               //初始化加载第一页，默认第一页,并记录
        pageSize: 15,                  //每页的记录行数（*）
        pageList: [5, 10, 15, 25, 50, 100], //可供选择的每页的行数（*）
        strictSearch: true,
        showColumns: true,          //是否显示所有的列（选择显示的列）
        showRefresh: true,                  //是否显示刷新按钮
        showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
        showFullscreen: true,        //是否全屏显示
        minimumCountColumns: 2,     //最少允许的列数
        clickToSelect: false,       //是否启用点击选中行
        //height: 500,                      //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        uniqueId: 'id',            //每一行的唯一标识，一般为主键列
        cardView: false,           //是否显示详细视图
        detailView: false,         //是否显示父子表
        smartDisplay: false,
        formSearchId: 'formSearch',　//搜索框参数，默认值等于：formSearch 2019.4.13 modify by zj
        queryParams: function (params) {             //得到查询的参数,这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var queryRequest = formInterface().form2JSon(this.formSearchId);   //读取搜索框参数，默认值等于：formSearch
            queryRequest['pageSize'] = params.limit;                        //页面大小
            queryRequest['pageNum'] = (params.offset / params.limit) + 1;  //页码
            queryRequest['sortName'] = (params.sort != null && params.sort != "" && typeof (params.sort) != "undefined") ? params.sort : 'id';          //排序列名（默认排序字段id）
            queryRequest['sortOrder'] = (params.order != null && params.order != "" && typeof (params.order) != "undefined") ? params.order : 'desc';   //排位命令（desc，asc）
            //queryRequest['search'] =null;

            //特殊格式的条件处理
            //queryRequest["WHC_Age"] = $("#WHC_Age").val() + "~" + $("#WHC_Age2").val();
            //queryRequest["WHC_BirthDate"] = $("#WHC_BirthDate").val() + "~" + $("#WHC_BirthDate2").val();
            return queryRequest;
        },
        onLoadError: function (status, jqXHR) {
            //数据加载失败！
        },
        onLoadSuccess: function (data) {
            //数据加载成功
        },
    };

    var validateRule_default = {
        errorClass: 'error', //指定错误提示的 css 类名，可以自定义错误提示的样式(默認error)
        errorElement: 'em',  //用什么标签标记错误，默认是 label，可以改成 em

        highlight: function (element) {
            $(element).parent().removeClass('state-success').addClass("state-error");
            $(element).removeClass('valid');
        },

        unhighlight: function (element) {
            $(element).parent().removeClass("state-error").addClass('state-success');
            $(element).addClass('valid');
        },

        errorPlacement: function (error, element) {
            error.appendTo(element.parent());
            //error.insertAfter(element.parent());
        }
    };

    //初始化表格
    function _initTable(tableId, settings) {
        var params = $.extend({}, bootstrapTable_default, settings);
        var tabObj = document.querySelector('#' + tableId.replace("#", ""));

        if (tabObj == null) {
            throw '初始化表格失败，请配置表格ID参数！';
        }

        if (typeof params.url === 'undefined') {
            throw '初始化表格失败，请配置url参数！';
        }

        if (typeof params.columns === 'undefined') {
            throw '初始化表格失败，请配置columns参数！';
        }

        $('#' + tableId.replace("#", "")).bootstrapTable(params);
    }

    //初始化表单验证规则
    function _initFormValidateRule(formId, settings) {
        try {
            var params = $.extend({}, validateRule_default, settings);
            var validator = $("#" + formId.replace("#", "")).validate(params);
            return validator;
        } catch (e) {

        }
    }

    // jquery treegird
    function _initTreeTable(tableId, setting) {
        $('#' + tableId.replace("#", "")).bootstrapTreeTable({
            id: setting.id, // 选取记录返回的值
            code: setting.code, // 用于设置父子关系
            parentColumn: !setting.parentColumn ? 'parentId' : setting.parentColumn, // 用于设置父子关系
            type: "POST", // 请求数据的ajax类型
            url: setting.url, // 请求数据的ajax的url
            ajaxParams: !setting.ajaxParams ? {} : setting.ajaxParams, // 请求数据的ajax的data属性
            expandColumn: !setting.expandColumn ? '1' : setting.expandColumn, // 在哪一列上面显示展开按钮
            striped: true, // 是否各行渐变色
            bordered: true,
            checkboxes: true,
            expandAll: setting.expandAll ? true : setting.expandAll, // 是否全部展开
            columns: setting.columns
        });
    }

    /*--------------------------------------
        Bootstrap Notify Notifications
    ---------------------------------------*/
    function _notify(title, message, type, callback) {
        try {
            swal({
                title: title,
                text: message,
                icon: type,   //一共有 4 个预定义好的参数："warning"，"error"， "success"和 "info"。分别表示 “警告”、“错误”、“成功” 和“信息”。
                button: "确定",
            }).then(function (value) {
                if (typeof (callback) != "undefined" && callback)
                    callback();
            });
        } catch (e) {
            alert(message);//如果无法使用了，那么这个就顶上去
        }
    }

    // close modal
    function _closeModal(modalId) {
        $("#" + modalId.replace("#", "")).find("button.btn-hide").attr("data-dismiss", "modal").trigger('click');
    }

    // close and reset modal
    function _closeAndRestModal(modalId) {
        var $modal = $("#" + modalId.replace("#", ""));

        $modal.find("button.btn-hide").attr("data-dismiss", "modal").trigger('click');
        $modal.find("form")[0].reset();
    }

    // 获取主题对应的16进制颜色
    function _getThemeColor(theme) {
        var color;

        switch (theme) {
            case 'green':
                color = '#32c787';
                break;
            case 'blue':
                color = '#2196F3';
                break;
            case 'red':
                color = '#ff5652';
                break;
            case 'orange':
                color = '#FF9800';
                break;
            case 'teal':
                color = '#39bbb0';
                break;
            case 'cyan':
                color = '#00BCD4';
                break;
            case 'blue-grey':
                color = '#607D8B';
                break;
            case 'purple':
                color = '#d559ea';
                break;
            case 'indigo':
                color = '#3F51B5';
                break;
            case 'lime':
                color = '#CDDC39';
                break;
            default:
                color = '#32c787';
        }

        return color;
    }

    // 获取主题对应的rgba(x,x,x,.1)颜色，用于日期选择插件
    function _getThemeRGBA(theme, opacity) {
        var color;

        switch (theme) {
            case 'green':
                color = 'rgba(50,199,135,' + opacity + ')';
                break;
            case 'blue':
                color = 'rgba(33,150,243,' + opacity + ')';
                break;
            case 'red':
                color = 'rgba(255,86,82,' + opacity + ')';
                break;
            case 'orange':
                color = 'rgba(255,152,0,' + opacity + ')';
                break;
            case 'teal':
                color = 'rgba(57,187,176,' + opacity + ')';
                break;
            case 'cyan':
                color = 'rgba(0,188,212,' + opacity + ')';
                break;
            case 'blue-grey':
                color = 'rgba(96,125,139,' + opacity + ')';
                break;
            case 'purple':
                color = 'rgba(213,89,234,' + opacity + ')';
                break;
            case 'indigo':
                color = 'rgba(63,81,181,' + opacity + ')';
                break;
            case 'lime':
                color = 'rgba(205,220,57,' + opacity + ')';
                break;
            default:
                color = 'rgba(50,199,135,' + opacity + ')';
        }

        return color;
    }

    // confirm弹窗
    function _confirm(settings, callback) {
        swal({
            title: '确认操作',
            text: settings.text,
            icon: "warning",
            dangerMode: settings.dangerMode,
            //buttons: true,
            buttons:
                {
                    cancel: {
                        text: "取消",
                        value: false,
                        visible: true,
                        className: "",
                        closeModal: true,
                    },
                    confirm: {
                        text: settings.confirmButtonText,
                        value: true,
                        visible: true,
                        className: "",
                        closeModal: true
                    }
                },
            closeOnEsc: false,
        })
            .then(function (isCconfirm) {
                if (isCconfirm && callback)
                    callback();
            });
    }

    // 恢复jsTree，还原到初始化状态
    function _resetJsTree(id) {
        $('#' + id).jstree("close_all");
        $('#' + id).jstree("deselect_all");
    }

    // 重新加载数据，重绘jsTree
    function _refreshJsTree(id, fn) {
        $('#' + id).data('jstree', false).empty();
        fn;
    }

    /**
     * 日历
     * @param obj eles 日期输入框
     * @param boolean dobubble    是否为双日期（true）
     * @param boolean secondNot    有无时分秒（有则true）
     * @return none
     */
    function _calenders(eles, dobubble, secondNot) {
        var singleNot, formatDate;

        if (dobubble === true) {
            singleNot = false;
        } else {
            singleNot = true;
        }

        if (secondNot === true) {
            formatDate = "YYYY-MM-DD HH:mm:ss";
        } else {
            formatDate = "YYYY-MM-DD";
        }

        $(eles).daterangepicker({
            "singleDatePicker": singleNot,
            "timePicker": secondNot,
            "timePicker24Hour": secondNot,
            "timePickerSeconds": secondNot,
            "showDropdowns": true,
            "timePickerIncrement": 1,
            "linkedCalendars": false,
            "autoApply": true,
            "autoUpdateInput": false,
            "locale": {
                "direction": "ltr",
                "format": formatDate,
                "separator": "~",
                "applyLabel": "选取",
                "cancelLabel": "取消",
                "fromLabel": "From",
                "toLabel": "To",
                "customRangeLabel": "Custom",
                "daysOfWeek": [
                    "日",
                    "一",
                    "二",
                    "三",
                    "四",
                    "五",
                    "六"
                ],
                "monthNames": [
                    "一月",
                    "二月",
                    "三月",
                    "四月",
                    "五月",
                    "六月",
                    "七月",
                    "八月",
                    "九月",
                    "十月",
                    "十一月",
                    "十二月"
                ],
                "firstDay": 1
            }
        }, function (start, end, label) {
            if (secondNot === true && dobubble === true) {
                $(eles).val($.trim(start.format('YYYY-MM-DD HH:mm:ss') + '~' + end.format('YYYY-MM-DD HH:mm:ss')));
            } else if (secondNot === false && dobubble === true) {
                $(eles).val($.trim(start.format('YYYY-MM-DD') + '~' + end.format('YYYY-MM-DD')));
            } else if (secondNot === false && dobubble === false) {
                $(eles).val(start.format('YYYY-MM-DD'));
            } else if (secondNot === true && dobubble === false) {
                $(eles).val(start.format('YYYY-MM-DD HH:mm:ss'));
            }
        });
    }

    function _setCurrentKeyId(o, key) {
        var $f = $("#" + o);

        if (typeof $f == "undefined")
            return;

        if ($f == null)
            return;

        $f.attr("currentKeyId", key);
    }

    function _getCurrentKeyId(o) {
        var $f = $("#" + o);
        if (typeof $f == "undefined")
            return 0;

        if ($f == null)
            return 0;

        var $key = $f.attr("currentKeyId");

        if (typeof $key == "undefined")
            return 0;

        if ($key == null)
            return 0;

        var $val = parseInt($key);

        if (typeof $val == 'NaN')
            $val = 0;

        return $val;
    }

    function _haveRight(per) {
        try {
            var str = sessionStorage.pers;

            if (!str) return false;

            $tempRight = JSON.parse(str);

            var $i = $.inArray(per, $tempRight);
            if (typeof $i === 'number') {
                if ($i >= 0)
                    return true;
                else
                    return false;
            } else
                return false;
        } catch (e) {
            return false;
        }
    }

    function _popWindow(title, url, width, height) {
        var pw = window.innerWidth;
        var ph = window.innerHeight;
        var setArea = [(typeof (width) == "undefined") ? '850px' : width, (typeof (height) == "undefined") ? '570px' : height]

        if (pw < 720) {
            //手机，那么，使用全屏
            setArea = [(pw - 20) + "px", (ph - 20) + "px"];
        }

        top.layer.open({
            type: 2,
            title: title,
            maxmin: true,
            shadeClose: false, // 点击遮罩关闭层
            area: setArea,
            content: url
        });
    }

    ///POST提交数据方式进行网络跳转
    function _httpPost(URL, PARAMS) {
        var temp = document.createElement("form");
        temp.action = URL;
        temp.method = "post";
        temp.style.display = "none";


        for (var x in PARAMS) {
            var opt = document.createElement("textarea");
            opt.name = x;
            opt.value = PARAMS[x];
            temp.appendChild(opt);
        }
        document.body.appendChild(temp);
        temp.submit();

        return temp;

    }

    //自动执行对象的单击事件
    function _runClick(id) {
        if (id) {
            id = id.replace("#", "");
            id = "#" + id;
            try {
                var btn = top.document.querySelector(id);//只是在顶层上找
                if (btn) {
                    var evt = new MouseEvent("click", {
                        bubbles: true,
                        cancelable: true,
                        view: window
                    });
                    //触发事件
                    btn.dispatchEvent(evt);
                }
                return;
            } catch (e) {
                return;
            }

        }
    }

    ////弹出子窗体 2019.04.14 add by Tangshouwu
    function _popChildWindow(title, url, width, height) {
        var pw = window.innerWidth;
        var ph = window.innerHeight;
        var setArea = [(typeof (width) == "undefined") ? '850px' : width, (typeof (height) == "undefined") ? '570px' : height]

        if (pw < 720) {
            //手机，那么，使用全屏
            setArea = [(pw - 20) + "px", (ph - 20) + "px"];
        }

        layer.open({
            type: 2,
            title: title,
            maxmin: true,
            shadeClose: false, // 点击遮罩关闭层
            area: setArea,
            content: url
        });
    }

    return {
        initTable: function (tableId, setting) {
            _initTable(tableId.replace("#", ""), setting);
        },
        httpPost: function (URL, PARAMS) {
            _httpPost(URL, PARAMS);
        },
        initTreeTable: function (tableid, setting) {
            _initTreeTable(tableid.replace("#", ""), setting);
        },

        getTableIndex: function (tableId, index) {
            var pageSize = $('#' + tableId.replace("#", "")).bootstrapTable('getOptions').pageSize;
            var pageNumber = $('#' + tableId.replace("#", "")).bootstrapTable('getOptions').pageNumber;

            return pageSize * (pageNumber - 1) + index + 1;
        },

        //专门用于刷新表格，或者重新检索数据（检索条件，请在查询参数中进行配置）
        refreshTable: function (tableId) {
            $('#' + tableId.replace("#", "")).bootstrapTable('refresh');
        },
        initFormValidateRule: function (formId, setting) {
            return _initFormValidateRule(formId.replace("#", ""), setting);
        },
        removeByUniqueId: function (tableId, ids) {
            var arrIds = ids.split();
            arrIds.forEach(function (id) {
                $('#' + tableId.replace("#", "")).bootstrapTable('removeByUniqueId', id);
            })
        },
        updateByUniqueId: function (tableId, params) {
            $('#' + tableId.replace("#", "")).bootstrapTable('updateByUniqueId', params);
        },
        n_default: function (message, callback) {
            _notify('提示框', message, "info", callback);
        },
        n_info: function (message, callback) {
            _notify('通知框', message, "info", callback);
        },
        n_success: function (message, callback) {
            _notify('成功消息框', message, "success", callback);
        },
        n_warning: function (message, callback) {
            _notify('警告', message, "warning", callback);
        },
        n_danger: function (message, callback) {
            _notify('危险提示', message, "warning", callback);
        },
        n_error: function (message, callback) {
            _notify('错误', message, "error", callback);
        },
        closeModal: function (modalId) {
            _closeModal(modalId.replace("#", ""));
        },

        closeAndRestModal: function (modalId) {
            _closeAndRestModal(modalId.replace("#", ""));
        },
        getThemeColor: function (theme) {
            return _getThemeColor(theme);
        },
        getThemeRGBA: function (theme, opacity) {
            return _getThemeRGBA(theme, opacity);
        },
        confirm: function (settings, callback) {
            _confirm(settings, callback);
        },
        resetJsTree: function (id) {
            _resetJsTree(id);
        },
        refreshJsTree: function (id, fn) {
            _refreshJsTree(id, fn);
        },
        calenders: function (eles, dobubble, secondNot) {
            _calenders(eles, dobubble, secondNot);
        },
        setCurrentKeyId: function (o, key) {
            _setCurrentKeyId(o, key);
        },
        getCurrentKeyId: function (o) {
            return _getCurrentKeyId(o);
        },
        haveRight: function (per) {
            return _haveRight(per);
        },
        getDomainName: function () {
            var pro = window.location.protocol;
            var host = window.location.host;
            var domain = pro + "//" + host;

            return domain;
        },

        //将指定的链接以弹屏方式显示
        popWindows: function (title, url, width, height) {
            return _popWindow(title, url, width, height);
        },

        //弹出子窗体 2019.04.14 add by Tangshouwu
        popChildWindow: function (title, url, width, height) {
            return _popChildWindow(title, url, width, height);
        },
        //执行顶层菜单的对象单击
        runClick: function (id) {
            _runClick(id);
        }
    }

})($);




